# -- coding: utf-8 --
"""
# MIAHX© 视线传感器数据帧消息的 FastDDS 发布/订阅器

**模块：MIAHX© / 框架基础服务层（FFST） / 交互框架信息表示模型（IFIRM）**

Version: 0.4.10,
Last updated: October 20, 2024

## Contributor(s)
* GUO Wenli <[wenli@iscas.ac.cn](mailto:wenli@iscas.ac.cn)>
* YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>

## Change log
### v0.4.10
- .20: [优化] Reader 构造方法传入 topic_name
- .13: [更新] 适配新的消息定义，重命名，重新实现 write
- .11: [更新] 重命名 (deprecated)
- .2: [更新] 适配新基类 (deprecated)
### v0.4.7
- .24: [优化] 更新 DevGazeWriter.write 方法实现 (deprecated)
### v0.4.6
- .16: [新增] 初始实现

---
Copyright © 2024-2025 MIAHX Contributors, ISCAS, and ASIC. All Rights Reserved.
Licensed under Apache-2.0.
"""

import miahx_fastdds as dds

from .. import Topics, Participant
from ..reader import Reader, ReaderListener
from ..writer import Writer


class GazeStreamReader(Reader):
    """
    视线样本数据流读取器
    """

    def __init__(self, participant: Participant, on_data_listeners=None):
        """
        创建视线样本数据流读取器

        :param participant: FastDDS 参与者
        :param on_data_listeners: 数据监听回调列表
        """
        topic_name = Topics.DEV_GAZE
        topic_data_type = dds.GazeDataFramePubSubType()
        super().__init__(participant, topic_name, topic_data_type,
                         listener=ReaderListener(topic_name, topic_data_type, on_data_listeners))


class GazeStreamWriter(Writer):
    """
    视线样本数据流写入器
    """

    def __init__(self, participant: Participant,
                 stag: int = None, srate: int = None, schns: list[str] = None):
        """
        创建视线样本数据流写入器

        :param participant: FastDDS 参与者
        :param stag: 传感器标签，由 STag 类型生成
        :param srate: 传感器采样率，单位 Hz
        :param schns: 传感器数据通道定义
        """
        super().__init__(participant, Topics.DEV_GAZE, dds.GazeDataFramePubSubType(),
                         stag=stag, srate=srate, schns=schns)

    def write(self, chunk: list[tuple[int, float, dict]],
              iid: int = None, uts: float = None):
        """
        写入视线数据样本

        :param chunk: 样本数据描述，列表，每个元素为一个元组，表示：(样本的全局校准单调递增序号，样本的全局校准 POSIX 时间戳，样本数据)
        :param iid: 全局校准的单调递增序号
        :param uts: 全局校准的 POSIX 时间戳
        """
        # header
        frame = dds.GazeDataFrame()
        frame.header(self._create_frame_header(uts, iid))
        # body
        samples = []
        for item in chunk:
            iid, uts, sdata = item
            sample = dds.GazeSample()
            sample.iid(iid)
            sample.uts(uts)
            self._fill_attributes(sample, sdata)
            samples.append(sample)
        frame.samples(samples)
        # send
        self._writer.write(frame)
